package com.lsh.controller;

import com.lsh.service.TxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/3/17 10:18 上午
 * @desc ：
 */
@RestController
@RequestMapping("/tx")
public class TXController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TxService txService;

    /**
     * @return
     */
    @GetMapping("/buyAnApple")
    public Map<String,String> buyAnApple(){
        HashMap<String, String> resp = new HashMap<>();

        try {
            txService.buyAnApple();
        }catch (RuntimeException e){
            resp.put("code","9999");
            resp.put("msg",e.getMessage());
            resp.put("date",null);
            return resp;
        }
        resp.put("code","0000");
        resp.put("msg","消费成功");
        resp.put("date",null);
        return resp;
    }

    /**
     * 初始化  Redis   money 1000     AppleStock 100
     */
    @GetMapping("/init")
    public String init(){
        redisTemplate.opsForValue().set("money","1000");
        redisTemplate.opsForValue().set("AppleStock","100");
        String money = (String) redisTemplate.opsForValue().get("money");
        String appleStock = (String) redisTemplate.opsForValue().get("AppleStock");
        System.out.println("当前余额："+money+" 元 ，当前库存："+appleStock+" 个。");

        return "当前余额："+money+" 元 ，当前库存："+appleStock+" 个。";
    }
    @GetMapping("/select")
    public String select(){
        String money = (String) redisTemplate.opsForValue().get("money");
        String appleStock = (String) redisTemplate.opsForValue().get("AppleStock");
        System.out.println("当前余额："+money+" 元 ，当前库存："+appleStock+" 个。");

        return "当前余额："+money+" 元 ，当前库存："+appleStock+" 个。";
    }


}
